using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

namespace Manaddiction.UI
{
    public class CardStorage : UIPanel
    {
        [Header("Cards")]
        public ScrollRect scroll_rect;
        public RectTransform scroll_content;
        public CardGrid grid_content;
        public GameObject card_prefab;
        
        [Header("Deckbuilding")]
        public TextMeshProUGUI deck_card_quantity;
        public GameObject deck_cards_prefab;
        public RectTransform deck_content;
        public GridLayoutGroup deck_grid;
        
        private List<CollectionCard> card_list = new List<CollectionCard>();
        private List<CollectionCard> all_list = new List<CollectionCard>();
        private List<DeckCardLine> deck_card_lines = new List<DeckCardLine>();        // 卡组中的卡牌行列表
        
        private Dictionary<string, int> current_deck = new Dictionary<string, int>(); // 卡组中的卡牌(卡牌ID,数量)
        
        //private bool saving = false;
        private bool spawned = false;
        private bool update_grid = false;
        private float update_grid_timer = 0f;
        
        private static CardStorage instance;
        
        protected override void Awake()
        {
            base.Awake();
            instance = this;//将当前实例赋值给静态变量instance，方便全局访问

            //删除之前网格中的元素，避免重复生成卡牌
            for (int i = 0; i < grid_content.transform.childCount; i++)
                Destroy(grid_content.transform.GetChild(i).gameObject);
            //删除卡组网格中的元素
            for (int i = 0; i < deck_grid.transform.childCount; i++)
                Destroy(deck_grid.transform.GetChild(i).gameObject);
        }
        
        protected override void Start()
        {
            base.Start();
    
            // 不要在这里调用 Show()，保持隐藏状态
            StartCoroutine(InitializeCoroutine());
        }

        private IEnumerator InitializeCoroutine()
        {
            yield return null;
    
            while (GameDataManager.Instance == null || !GameDataManager.Instance.IsInitialized)
            {
                yield return null;
            }
    
            ReloadUserCards();
            ReloadUserDeck();
    
            // 初始化完成后，仍然保持隐藏状态
            // 只有当需要的时候（比如通过Tab按钮）才显示
        }
        
        private void LateUpdate()
        {
            // 累计更新时间（用于控制网格更新频率）
            update_grid_timer += Time.deltaTime;

            // 当需要更新网格且延迟时间超过0.2秒时执行（避免频繁计算）
            if (update_grid && update_grid_timer > 0.2f)
            {
                // 获取当前卡牌网格的行数和列数
                grid_content.GetColumnAndRow(out int rows, out int cols);

                // 如果至少有一列卡牌（确保有内容需要布局）
                if (cols > 0)
                {
                    // 计算单行高度 = 卡牌高度 + 行间距
                    float row_height = grid_content.GetGrid().cellSize.y + grid_content.GetGrid().spacing.y;
            
                    // 计算总高度 = 行数 × 单行高度
                    float height = rows * row_height;
            
                    // 设置滚动区域的高度（保持原始宽度，高度增加100像素缓冲空间）
                    scroll_content.sizeDelta = new Vector2(scroll_content.sizeDelta.x, height + 100);
            
                    // 重置更新标记（避免重复计算）
                    update_grid = false;
                }
            }
        }
        
        public void ReloadUserCards()
        {
            //加载用户卡牌数据
            RefreshCards();
        }
        
        /// <summary>
        /// 加载用户卡组数据
        /// </summary>
        private void ReloadUserDeck()
        {
            current_deck.Clear();
            if (GameDataManager.Instance.userData.deck.deck_cards == null)
            {
                GameDataManager.Instance.userData.deck.deck_cards = new List<CardDataTmp>();
                Debug.Log("No deck cards loaded");
            }
            else if (GameDataManager.Instance.userData.deck.deck_cards != null)
            {
                var deck_cards =  GameDataManager.Instance.userData.deck.deck_cards;
                for (int i = 0; i < deck_cards.Count; i++)
                {
                    current_deck.Add(deck_cards[i].card_name, deck_cards[i].quantity);
                }
            }
            RefreshDeckCards(); // 更新卡组卡牌显示
        }
        
        // 保存卡组到 UserData
        public void SaveDeck()
        {
            foreach (KeyValuePair<string, int> pair in current_deck)
            {
                CardDataTmp card = new CardDataTmp();
                card.card_name = pair.Key;
                card.quantity = pair.Value;
                GameDataManager.Instance.userData.deck.deck_cards.Add(card);
            }

            if (GameDataManager.Instance.userData.deck.GetQuantity() == 20)
            {
                GameDataManager.Instance.SavePlayerData(); // 保存到本地文件
                TipsPanel.Get().ShowTips("Deck Save Succeed");
                Debug.Log("卡组已保存");
            }
            else
            {
                TipsPanel.Get().ShowTips("Deck Save Failed");
                Debug.Log("卡组保存失败");
            }
        }
        
        private void CreateDeckCard()//在侧边栏中创造DeckCardLine预制体
        {
            GameObject deck_line = Instantiate(deck_cards_prefab, deck_grid.transform);
            DeckCardLine line = deck_line.GetComponent<DeckCardLine>();
            deck_card_lines.Add(line);
            // 调整内容区域高度
            //float height = deck_card_lines.Count * 70f + 20f;
            //deck_content.sizeDelta = new Vector2(deck_content.sizeDelta.x, height);
            line.onClick += OnClickCardLine;
        }
        
        private void OnClickCardLine(DeckCardLine line)//点击卡组中卡片事件
        {
            CardData card = line.GetCard();
            if (card != null)
            {
                RemoveDeckCard(card);
            }
            RefreshCards();
            RefreshDeckCards();
        }
        
        // 添加卡牌到卡组
        private void AddDeckCard(CardData card)
        {
            string tid = UserCardData.GetTid(card.id);
            AddDeckCard(tid);
        }

        // 从卡组移除卡牌
        private void RemoveDeckCard(CardData card)
        {
            string tid = UserCardData.GetTid(card.id);
            RemoveDeckCard(tid);
        }

        // 添加卡牌到卡组(通过卡牌ID)
        private void AddDeckCard(string tid)
        {
            if (current_deck.ContainsKey(tid))
                current_deck[tid] += 1;
            else
                current_deck[tid] = 1;
        }

        // 从卡组移除卡牌(通过卡牌ID)
        private void RemoveDeckCard(string tid)
        {
            if (current_deck.ContainsKey(tid))
                current_deck[tid] -= 1;
            if (current_deck[tid] <= 0)
                current_deck.Remove(tid);
        }

        public void RemoveAllDeckCards()
        {
            current_deck.Clear();
            RefreshCards();
            RefreshDeckCards();
        }

        
        // 更新卡组显示
        private void RefreshDeckCards()
        {
            // 隐藏所有卡牌行
            foreach (DeckCardLine line in deck_card_lines)
                line.Hide();
            
            // 准备卡牌数据列表
            List<CardDataQ> list = new List<CardDataQ>();
            foreach (KeyValuePair<string, int> pair in current_deck)
            {
                CardDataQ acard = new CardDataQ();
                acard.card = UserCardData.GetCardData(pair.Key);
                acard.quantity = pair.Value;
                list.Add(acard);
            }
            
            // 按魔力排序
            list.Sort((CardDataQ a, CardDataQ b) => { return a.card.mana.CompareTo(b.card.mana); });
            
            int index = 0;
            int count = 0;

            // 显示卡组中的卡牌
            foreach (CardDataQ card in list)
            {
                if (index >= deck_card_lines.Count)
                    CreateDeckCard();

                if (index < deck_card_lines.Count)
                {
                    DeckCardLine line = deck_card_lines[index];
                    if (line != null)
                    {
                        line.SetLine(card.card, card.quantity);
                        count += card.quantity;
                    }
                }
                index++;
            }

            // 更新卡牌数量显示
            deck_card_quantity.text = $"{current_deck.Values.Sum()}/20";
        }
        
        private void SpawnCards()
        {
            // 标记卡牌已生成，避免重复创建
            spawned = true;
    
            // ---------- 第一步：清理现有卡牌 ----------
            // 销毁所有已存在的卡牌UI对象
            foreach (CollectionCard card in all_list)
            {
                Destroy(card.gameObject);
            }
            // 清空卡牌列表
            all_list.Clear();

            // ---------- 第二步：生成新卡牌 ----------
            // 遍历游戏中的所有卡牌数据
            foreach (CardData card in GameDataManager.GetAllCards())
            {
                // 实例化卡牌预制体，并放入网格容器
                GameObject nCard = Instantiate(card_prefab, grid_content.transform);
                // 获取卡牌UI组件
                CollectionCard dCard = nCard.GetComponent<CollectionCard>();
                // 初始化卡牌数据（卡牌、变体、初始数量0）
                dCard.SetCard(card, 0);
                // 绑定点击事件：
                // 左键点击 - 选择卡牌
                dCard.onClick += OnClickCard;
                // 右键点击 - 查看卡牌详情
                dCard.onClickRight += OnClickCardRight;
                // 加入总列表
                all_list.Add(dCard);
                // 默认隐藏，等待筛选后显示
                nCard.SetActive(false);
            }
        }
        
        /// <summary>
        /// 刷新卡牌显示（根据当前筛选条件）
        /// 执行流程：
        /// 1. 检查并初始化卡牌UI
        /// 2. 获取当前筛选条件
        /// 3. 处理卡牌排序
        /// 4. 应用多重筛选条件
        /// 5. 更新卡牌显示状态
        /// 6. 触发布局刷新
        /// </summary>
        public void RefreshCards()
        {
            // 如果卡牌未初始化，先执行生成
            if (!spawned)
                SpawnCards();

            // 重置显示状态：隐藏所有卡牌并清空显示列表
            foreach (CollectionCard card in all_list)
                card.gameObject.SetActive(false);
            card_list.Clear();

            // 获取用户数据
            UserData udata = GameDataManager.Instance.userData;

            // 准备数据容器
            List<CardDataQ> all_cards = new List<CardDataQ>();  // 所有卡牌（含数量信息）
            //List<CardDataQ> shown_cards = new List<CardDataQ>(); // 最终显示的卡牌

            // 构建卡牌数据列表（包含拥有数量）
            foreach (CardData icard in GameDataManager.GetAllCards())
            {
                CardDataQ card = new CardDataQ();
                card.card = icard;
                // 获取玩家拥有该卡牌的数量
                card.quantity = udata.GetCardQuantity(UserCardData.GetTid(icard.id));
                all_cards.Add(card);
            }

            // --- 排序处理 ---
            //按费用排序（费用相同则按名称）
            all_cards.Sort((a, b) => b.card.mana == a.card.mana 
                ? a.card.card_name.CompareTo(b.card.card_name) 
                : a.card.mana.CompareTo(b.card.mana));

            // --- 更新UI显示 ---
            int index = 0;
            foreach (CardDataQ qcard in all_cards)
            {
                if (index < all_list.Count)
                {
                    CollectionCard dcard = all_list[index];
                    // 更新卡牌显示数据
                    int indeck = 0;
                    if (current_deck.ContainsKey(qcard.card.id))
                    {
                        indeck = current_deck[qcard.card.id];
                        dcard.SetCard(qcard.card, 
                            udata.GetCardQuantity(UserCardData.GetTid(qcard.card.id)) - indeck);
                    }
                    else
                    {
                        dcard.SetCard(qcard.card, 
                            udata.GetCardQuantity(UserCardData.GetTid(qcard.card.id)));
                    }

                    card_list.Add(dcard);

                    int quantity = int.Parse(dcard.quantity.text);
                    if(quantity > 0)
                        dcard.gameObject.SetActive(true); // 显示卡牌
                    index++;
                }
            }
            
            // 标记需要更新网格布局
            update_grid = true;
            update_grid_timer = 0f;
            // 重置滚动条位置到顶部
            scroll_rect.verticalNormalizedPosition = 1f;
            // 更新卡牌透明度（未拥有的变灰）
            //RefreshCardsOpacity();
        }
        
        // 计算卡组中特定卡牌的数量(相同变体)
        public int CountDeckCards(CardData card)
        {
            string tid = UserCardData.GetTid(card.id);
            if (current_deck.ContainsKey(tid))
                return current_deck[tid];
            return 0;
        }
        
        // 卡牌点击事件
        public void OnClickCard(CardUI card)
        {
            //添加卡牌到卡组
            CardData icard = card.GetCard();
            if (icard != null)
            {
                int in_deck = CountDeckCards(icard);

                // 检查是否超过卡组限制
                bool deck_limit = in_deck < 2;

                if (deck_limit)
                {
                    AddDeckCard(icard);
                    RefreshCards();
                    RefreshDeckCards();
                }
            }
        }
        
        public void OnClickCardRight(CardUI card)
        {
            CardZoomPanel.Get().ShowCard(card.GetCard());
        }
        
        public struct CardDataQ
        {
            public CardData card;
            public int quantity;
        }
    }
}
